<template>
  <div class="chat-app">
    <div class="sidebar">
      <FriendList :friends="friends" @select-friend="selectFriend" />
    </div>
    <div class="main">
      <MessageBox
          v-if="selectedFriend"
          :friend="selectedFriend"
          :messages="messages"
          @send-message="sendMessage"
      />
      <div v-else class="placeholder">请选择一个好友开始聊天</div>
    </div>
  </div>
</template>

<script>
import FriendList from "@/components/FriendList.vue";
import MessageBox from "@/components/MessageBox.vue";

export default {
  components: {
    FriendList,
    MessageBox,
  },
  data() {
    return {
      friends: [
        { id: 1, name: "好友1" },
        { id: 2, name: "好友2" },
        { id: 3, name: "好友3" },
      ],
      selectedFriend: null,
      messages: [],
      socket: null, // WebSocket 实例
    };
  },
  watch: {
    selectedFriend(newFriend) {
      if (newFriend) {
        this.messages = this.getMessagesForFriend(newFriend.id);
      }
    },
  },
  mounted() {
    this.initWebSocket();
  },
  beforeUnmount() {
    if (this.socket) {
      this.socket.close(); // 关闭 WebSocket 连接
    }
  },
  methods: {
    initWebSocket() {
      // 从 localStorage 中获取登录的用户信息
      const userId = localStorage.getItem("userId");
      if (!userId) {
        this.$router.push("/login"); // 如果未登录，跳转到登录页
        return;
      }

      // 初始化 WebSocket 连接
      this.socket = new WebSocket("ws://your-websocket-url");

      this.socket.onopen = () => {
        console.log("WebSocket 连接已建立");

        // 发送登录消息到服务器
        this.socket.send(
            JSON.stringify({
              type: "login",
              userId: userId,
            })
        );
      };

      this.socket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.messages.push(message); // 接收消息并添加到消息列表
      };

      this.socket.onclose = () => {
        console.log("WebSocket 连接已关闭");
      };

      this.socket.onerror = (error) => {
        console.error("WebSocket 错误:", error);
      };
    },
    selectFriend(friend) {
      this.selectedFriend = friend;
    },
    sendMessage(message) {
      if (this.selectedFriend && message.trim()) {
        const messageData = {
          id: this.messages.length + 1,
          text: message,
          sender: localStorage.getItem("userId"), // 当前用户 ID
          receiver: this.selectedFriend.id,
          type: "message",
        };

        // 发送消息到 WebSocket 服务器
        this.socket.send(JSON.stringify(messageData));

        // 将消息添加到本地消息列表
        this.messages.push(messageData);
      }
    },
    getMessagesForFriend(friendId) {
      // 模拟消息数据
      return [
        { id: 1, text: "你好！", sender: "friend", receiver: friendId },
        { id: 2, text: "最近怎么样？", sender: "me", receiver: friendId },
        { id: 3, text: "还不错，你呢？", sender: "friend", receiver: friendId },
      ];
    },
  },
};
</script>

<style scoped>
.chat-app {
  display: flex;
  height: 100vh;
  font-family: Arial, sans-serif;
}

.sidebar {
  width: 200px;
  background-color: #2c3e50;
  color: white;
  padding: 10px;
}

.main {
  flex: 1;
  padding: 10px;
  background-color: #ecf0f1;
}

.placeholder {
  text-align: center;
  margin-top: 20px;
  color: #7f8c8d;
}
</style>